package shuiyuqing.data;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.whu.administrator.ws.MyApplication;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import inter.Delegate;
import inter.ResponseStatus;
import shuiyuqing.dto.STINFO;
import shuiyuqing.network.GetAllSTAndPointInfo;
import utils.PreferenceHelper;

/**
 * 所有的站点
 * Created by Administrator on 2016/3/21.
 */
public class AllPoints {

    static NotifyGet notifyGet;

    public static void setNotifyGet(NotifyGet notifyGet2) {
        notifyGet = notifyGet2;
    }

    private static Delegate delegate = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (!response.startsWith("{")) return;

            Gson gson = new Gson();
            GetAllSTAndPointInfo.ResponseSTInfo responseSTInfo = gson.fromJson(response, GetAllSTAndPointInfo.ResponseSTInfo.class);
            if (responseSTInfo.getStatus().equals(ResponseStatus.SUCCESS))
            {
                List<STINFO> stinfos = responseSTInfo.getSTList();
                PreferenceHelper preferenceHelper = new PreferenceHelper(MyApplication.share());
                preferenceHelper.putString(PreferenceHelper.allPoints, "data", JSON.toJSONString(stinfos));

                allPoints = new AllPoints();
                allPoints.setStinfos(stinfos);
                if (notifyGet != null)
                    notifyGet.get(allPoints);

                delegate = null;
            }

        }

        @Override
        public void onErrorResponse(VolleyError error) {
            delegate = null;
        }
    };
    List<STINFO> stinfos = new ArrayList<STINFO>();
    static AllPoints allPoints  = null;


    public List<STINFO> getStinfos() {
        return stinfos;
    }

    public void setStinfos(List<STINFO> stinfos) {
        this.stinfos = stinfos;
    }

    public static AllPoints getAllPoints()
    {
        PreferenceHelper preferenceHelper = new PreferenceHelper(MyApplication.share());
        if (allPoints != null )
            return allPoints;
        else if (preferenceHelper.contains(PreferenceHelper.allPoints,"data"))
        {
            allPoints = new AllPoints();
            String str_allPoints = preferenceHelper.getString(PreferenceHelper.allPoints,"data");
            List<STINFO> stinfosTmp = JSON.parseArray(str_allPoints,STINFO.class);
            allPoints.setStinfos(stinfosTmp);
        }
        else
        {
            GetAllSTAndPointInfo getAllSTAndPointInfo = new GetAllSTAndPointInfo();
            getAllSTAndPointInfo.setDelegate(delegate);
            getAllSTAndPointInfo.get();
        }
        return allPoints;
    }


    // 从网络获取数据，回调
    public interface NotifyGet
    {
        public void get(AllPoints allPoints);
    }

}
